package jpa4azure.impl;

import static jpa4azure.type.TypeWrapperFactory.wrap;

import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceException;

import jpa4azure.type.Key;
import jpa4azure.type.TypeWrapper;

import com.windowsazure.samples.HttpStatusCode;
import com.windowsazure.samples.table.AzureTableEntity;
import com.windowsazure.samples.table.AzureTableManager;

public class FindOperation {
	AzureTableManager client;
	AzureEntityManager aem;

	public FindOperation(AzureEntityManager aem) {
		this.client = aem.getTableStorageClient();
		this.aem = aem;
	}

	
	public <T> T findit(Class<T> c, Key id) {
		TypeWrapper type = wrap(c);
		try {
			return findit(type, id);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public <T> T findit(Class<T> c, Object o) {
		TypeWrapper type = wrap(c);
		Key id = new Key(o.toString());
		try {
			return findit(type, id);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	public <T> T findit(TypeWrapper type, Key key) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		String table = type.getTableName();		
		AzureTableEntity e = client.getEntity(table, key.getPartition(), key.getRow());
		if (e.getHttpStatusCode() == HttpStatusCode.NotFound) {
			throw new EntityNotFoundException("Cannot find " + type.getTableName()
					+ " with key " + key.getRow());
		}
		return (T)aem.convert(e);
	}


}
